<?php declare(strict_types=1);


namespace App\Services\Refund\Strategy;

use App\Api\Controllers\WftPay\PayController as WftPayPayController;
use App\Common\RefundSuccessAction;
use App\Exceptions\BizException;
use App\Models\MerchantWalletDetail;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Models\UserWalletDetail;
use Illuminate\Support\Facades\Log;

class CibRefundStrategy implements RefundStrategyInterface
{
    public function refundQuery(array $data): array
    {
        $store = Store::query()->where("store_id", $data["store_id"])->first();
        if (empty($store)) {
            throw new BizException("门店不存在");
        }
        $config = new \App\Api\Controllers\Config\CibPayConfigController();
        $cibpay_config = $config->wftpay_config($store->config_id);
        if (!$cibpay_config) {
            throw new BizException("兴业支付配置不存在请检查配置");
        }
        $cibpay_merchant = $config->cib_merchant($store->store_id, $store->pid);
        if (!$cibpay_merchant) {
            throw new BizException("兴业支付商户号不存在");
        }
        $obj = new WftPayPayController();
        $return_query_data = [
            'mch_id' => $cibpay_merchant->mch_id,
            'out_trade_no' => $data["out_trade_no"],
            'out_refund_no' => $data["refund_no"],
            'private_rsa_key' => $cibpay_config->private_rsa_key,
            'public_rsa_key' => $cibpay_config->public_rsa_key
        ];
        //$return_query_res = $this->refund_query($return_query_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败
        $return = $obj->refund_query($return_query_data);

        $status = -1;
        $refund_error_msg = $other_refund_no = $refund_detail = $refund_time = "";

        if ($return["status"] == 1) {
            $status = 1;
            $refund_count = $return['data']['refund_count'] - 1; //退款记录数
            $other_refund_no = $return['data']['refund_id_' . $refund_count];
            $refund_time = date("Y-m-d H:i:s", strtotime($return['data']['refund_id_' . $refund_count]));
            $refund_detail = "";
        } else if ($return["status"] == 2) {
            $status = -1;
            $refund_error_msg = "退款失败";
        } else if ($return["status"] == 3) {
            $status = 0;
            $refund_error_msg = "退款中";
        } else if ($return["status"] == 4) {
            $status = 0;
            $refund_error_msg = "退款银行卡冻结";
        }
        return [
            "status" => $status,
            "other_refund_no" => $other_refund_no,
            "refund_detail" => $refund_detail,
            "refund_time" => $refund_time,
            "refund_error_msg" => $refund_error_msg
        ];
    }


}